function mat2wv(vfcSignal, sFilename, fSampleRate, bNormalize)
% mat2wv(vfcSignal, sFilename, fSampleRate, bNormalize)
% MAT2WV creates an SMU waveform file from a Matlab vector.
%
% Input parameters:
% vfcSignal: Input data vector
% sFilename: Filename of the generated waveform file
% fSampleRate: Sample rate of the signal in Hz
% bNormalize:
%   True: The signal is normalized by the max. magnitude
%  False: The signal is not normalized. The maximum magnitude
%         of the signal shall not exceed 1.0.
% Copyright    : Rohde & Schwarz GmbH & Co. KG, Munich, Germany
% File version : \main\4    21 Jul 2008 16:20:08   ramian
% Revision     : V2.0
% Date         : 2008/08/18 12:03:56

% Force row vector
vfcSignal = vfcSignal(:).';

% Number of samples
iNOfSamples = length(vfcSignal);

% Normalize signal
if bNormalize

  fprintf('Normalize signal\n');
  vfcSignal = vfcSignal / max(abs(vfcSignal));
  % Remark:
  % We do not normalize to max RE/IM to allow arbitrary phase offsets
  % or frequency shifts without overflow
    
  vfcSignal = vfcSignal / max(abs(vfcSignal));
  
  % Calculate the peak value
  fPeakPower = max(abs(vfcSignal).^2);
  fPeakPowerdBfs = -10*log10(fPeakPower);
  % Calculate the RMS value
  fMeanPower = mean(abs(vfcSignal).^2);
  fRMSdBfs = -10*log10(fMeanPower);

else
  
  % Do not normalize the signal
  fPeakPowerdBfs = 0;
  fRMSdBfs = 0;
  
end

% Quantization to 16 bit
iMaxInt = 32767;
vicData = vfcSignal*iMaxInt;
clear vfcSignal;

viDataInterleaved = reshape([real(vicData);imag(vicData)],1,2*iNOfSamples);
clear vicData;

viDataInterleaved = int16(viDataInterleaved);

% Write waveform file
fid = fopen(sFilename,'w');
fprintf(fid,'%s','{TYPE: SMU-WV,0}');
fprintf(fid,'%s','{COMMENT: Generated by mat2wv.m}');
fprintf(fid,'%s',['{DATE: ' datestr(now,'yyyy-mm-dd;HH:MM:SS') '}']);
fprintf(fid,'%s',['{LEVEL OFFS: ' num2str(fRMSdBfs) ', ' num2str(fPeakPowerdBfs) '}']);
fprintf(fid,'%s',['{CLOCK: ' num2str(fSampleRate) '}']);
fprintf(fid,'%s',['{SAMPLES: ' num2str(iNOfSamples) '}']);
fprintf(fid,'%s',['{WAVEFORM-' num2str(4*iNOfSamples+1) ':#']);
fwrite(fid,viDataInterleaved,'int16');
fprintf(fid,'%s','}');
fclose(fid);

